package tk1.uebung05.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.Date;

public class ClientNTPThread extends Thread {

	private NTPMessagePair[] ntpMessagePairs = new NTPMessagePair[10];
	private Socket server;
	private int count = 0;
	private int lastFinished = -1;

	public NTPMessagePair[] getNtpMessagePairs() {
		return ntpMessagePairs;
	}

	public void run() {
		String ip = "127.0.0.1"; // localhost
		int port = 11111;
		try {
			server = new Socket(ip, port); // verbindet sich mit Server
		} catch (IOException e) {
			e.printStackTrace();
		}
		while (count < 10) {
			try {
				writeRequest();
				readResponse();
				count++;
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			try {
				sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	private void writeRequest() throws IOException {
		PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(
				server.getOutputStream()));
		long requestTime = (new Timestamp((new Date()).getTime())).getTime();
		String requestTimeAsString = String.valueOf(requestTime);

		long transmissionDelay = (long) ((Math.random() * 90) + 10);
		try {
			sleep(transmissionDelay);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		printWriter.print(requestTimeAsString);
		printWriter.flush();
	}

	private void readResponse() throws IOException {
		
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(server.getInputStream()));
		char[] buffer = new char[200];
		int anzahlZeichen = bufferedReader.read(buffer, 0, 200); // blockiert
																	// bis
																	// Nachricht
																	// empfangen
		
		long ti = (new Timestamp((new Date()).getTime())).getTime();
		String response = new String(buffer, 0, anzahlZeichen);
		String[] formerTimestamps = response.split(",");
		long ti_3 = Long.valueOf(formerTimestamps[0]).longValue();
		long ti_2 = Long.valueOf(formerTimestamps[1]).longValue();
		long ti_1 = Long.valueOf(formerTimestamps[2]).longValue();

		ntpMessagePairs[count] = new NTPMessagePair(ti_3, ti_2, ti_1, ti);

		lastFinished = count;
	}
	
	public int getLastFinishedMeasurementIndex(){
		return lastFinished;
	}
}
